var trendTime;
var inTrend;
var outTrend;

var areaDensity;
var passengerDensity;

var person;
var planWork;
var planComplete;
var perceptionWork;
var perceptionComplete;


var planTaskTotal=[];
var senseTaskTotal=[];
var planTaskDone=[];
var senseTaskDone=[];
var timeLine=[];
var planTaskUndone=[];
var senseTaskUndone=[];
var planData=[];
var senseData=[];
var iframeUrl;
var isProd = true; //是否为生产环境，生产环境将采用内网IFRAME URL
var icon = picIcon;
$(function() {
	mytime();
	// 系统时间
	setInterval(function() {
		mytime();
	}, 1000);
	//温湿度
	getMonitorData();
	setInterval(function() {
		getMonitorData();
	}, 30*60*1000);
	//系统总览
	getSystemOverviewData();
	setInterval(function() {
		getSystemOverviewData();
	}, 5000);
	// 系统运营模式
	getOperationModeData();
	setInterval(function() {
		getOperationModeData();
	}, 5000);
	// 车站运营事件
	getOperationalEventData();
	setInterval(function() {
		getOperationalEventData();
	}, 5000);
	// 车站客流趋势数据
	getTrendData();
	setInterval(function() {
		getTrendData();
	}, 60*1000);
	// 区域客流密度数据
	getRegionalPassFlowDensity();
	setInterval(function() {
		getRegionalPassFlowDensity();
	}, 10*60*1000);
	// 任务信息数据
	getPersonInfoData();
	setInterval(function() {
		getPersonInfoData();
	}, 60*60*1000);
	// 报障信息
	getWorkInfoData();
	setInterval(function() {
		getWorkInfoData();
	}, 60*60*1000);
	//引入iframe
	creatIframe();
});


$("div.system").click(function(){
	document.location.href= "device.html" ;
});
$("div.person").click(function(){
	document.location.href= "personnel.html" ;
});
$(".gzzx").click(function(){
	document.location.href= "gzzx.html" ;
});

$("div.passMode").click(function(){
    $("#bg").css({
        display: "block", height: $(document).height()
    });
    var $box = $('.mode_list');
    $box.css({
        display: "block",
    });
});

$(".mode_list li").on('click',function () {
    $("#bg,.mode_list").css("display", "none");
    $("div.passMode").text($(this).html());
});

//生成iframe url
function setIframeUrl(){
	if(isProd){
		//生产环境url
		var origin = window.location.origin;
		origin = origin.replace(window.location.port,"9020"); //SVG与此项目同IP不同端口
		iframeUrl = origin + "/bip/last-location.html";
	}else{
		//测试环境url
		iframeUrl = "http://dev.lziot.cn:8080/bip/last-location.html";
	}
}

//引入iframe
function creatIframe(){
	setIframeUrl();
	$("div.iframe").append(
		"<iframe align=\"left\" width=\"1155px\" height=\"900px\" frameborder=\"no\" src="+iframeUrl+"></iframe>"
	)
}

function mytime() {
	var a = new Date();
	var time = a.toLocaleTimeString();
	var date = a.toLocaleDateString();
	$("span.date").html(date);
	$("span.time").html(time);
}

function getMonitorData(){
	sendAjaxRequest('index/monitor', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.temperature").html(jsonObj.data.monitorData.temperature);
			$("div.precipitation").html(jsonObj.data.monitorData.precipitation);
			//$("div.pm2").html(jsonObj.data.monitorData.pm2);
			$("div.ppm p:eq(0)").html(jsonObj.data.monitorData.ppm);
		}else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

function getSystemOverviewData() {
	sendAjaxRequest('index/systemOverview', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.systemOverview").empty();
			var imgNO = 7;
			$.each(jsonObj.data.systemOverviewData,function(i, obj) {
				var src = "../images/" + imgNO + ".png";
				var srcRed = "../images/" + (imgNO + 1)+ ".png";
				if (obj) {
					$("div.systemOverview").append(
					"<div class='systemOverview-item'><img src=" + src + " alt=''>" +
						"<p class='systemOverview-font'>" + i + "</p>" +
					"</div>");
				} else {
					$("div.systemOverview").append(
					"<div class='systemOverview-item'><img src=" + srcRed + " alt=''>" +
						"<p class='systemOverview-font' style='color: #E60012'>" + i + "</p>" +
					"</div>");
				}
				imgNO = imgNO + 2;
			})
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

function click() {
	console.log("xxx");
}

function getOperationModeData() {
	sendAjaxRequest('index/operationMode', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.publicArea").empty();
			$("div.intelligence").empty();
			$("div.publicArea").append(
				"<p>" + jsonObj.data.operationModeData.publicArea[0] + "</p>" +
				"<p>" + jsonObj.data.operationModeData.publicArea[1] + "</p>");
			$("div.intelligence").append(
				"<p>" + jsonObj.data.operationModeData.intelligence + "</p>");
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

function getOperationalEventData() {
	sendAjaxRequest('index/operationalEvent', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.operationalEvents").empty();
			$.each(jsonObj.data.operationalEventData, function(i, obj) {
				var arr = obj.split("@");
				if(arr[2] == null) //第三个元素为报警图片ID，为空时不绑定有图片的元素及事件
				{
					$("div.operationalEvents").append(
							"<div class='eventTable'>" + 
								"<div class='tableLeft'>" + arr[0] + "</div>" + 
								"<div class='tableRight'>" + arr[1] + "</div>" + 
							"</div>");
				}else{
					$("div.operationalEvents").append(
							"<div class='eventTable cctvPic' onclick='getCCTVPic(\""+arr[1]+"\",\""+arr[2]+"\")'>" + 
								"<div class='tableLeft'>" + arr[0] + "&nbsp;<img src='"+icon+"'/></div>" + 
								"<div class='tableRight'>" + arr[1] + "</div>" + 
							"</div>");
				}
			});
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

function getCCTVPic(message,alarmId)
{
	console.log(alarmId);
	var json = {'alarmId':alarmId}
	sendAjaxRequest("index/getPic",json,null,function(data){
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("#cctvImg").attr("src","data:image/jpg;base64,"+jsonObj.data);
			layer.open({
			      type: 1,
			      area: ['1282px', '770px'],
			      shadeClose: true, //点击遮罩关闭
			      title:message,
			      content: $("#cctvPic")
			    });
		} else if (jsonObj.type == "error") {
			console.log(jsonObj.message);
		}
	});

}

function getTrendData() {
	sendAjaxRequest('index/trend', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			trendTime = jsonObj.data.trendData.trendTime;
			inTrend = jsonObj.data.trendData.inTrend;
			outTrend = jsonObj.data.trendData.outTrend;
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	});
    var passengerTrend = echarts.init(document.getElementById('trend'));
    trendChart(passengerTrend);
}

function getRegionalPassFlowDensity() {
	sendAjaxRequest('personnel/regionalData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		console.log(jsonObj.data);
		if (jsonObj.code == "success") {
			regionalData = jsonObj.data.dataList;
		} else {
			console.log(jsonObj.message);
		}
	});
    var regionalPassFlowDensityData = {
    		seriesData : regionalData
    }
    var passengerdensity = echarts.init(document.getElementById('density'));
    densityChart(passengerdensity,regionalPassFlowDensityData)
}

function getPersonInfoData() {
	sendAjaxRequest('index/taskComp', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			var list = jsonObj.data;
			if(list){
				for(var i in list){
					var typeInfo=i.split("_");
					var task=list[i]							
					timeLine.push(typeInfo[3]+":00:00")
					if(typeInfo[1]=="9"&&typeInfo[2]=="1"){
						planTaskTotal.push(task)
					}
					if(typeInfo[1]=="1"&&typeInfo[2]=="1"){
						planTaskDone.push(task)
					}
					if(typeInfo[1]=="9"&&typeInfo[2]=="3"){
						senseTaskTotal.push(task)
					}
					if(typeInfo[1]=="1"&&typeInfo[2]=="3"){
						senseTaskDone.push(task)
					}
					
				}
				timeLine=timeLine.filter(function(element,index,self){
				     return self.indexOf(element) === index;
				  });

				for(var i in planTaskTotal){
					planTaskUndone.push(Number(planTaskTotal[i])-Number(planTaskDone[i]))
					senseTaskUndone.push(Number(senseTaskTotal[i])-Number(senseTaskDone[i]))
				}
				for(var i in planTaskTotal){
					planData.push(planTaskTotal[i])
				}
				for(var k in senseTaskTotal){
					senseData.push(senseTaskTotal[k])
				}
				
				if(planData!=""&&planData!=[]){
					var planMax=Math.max.apply(null,planData)
					var planAdd=parseInt(planMax/10)
					if(planAdd==0){planAdd=1}
				}
				if(senseData!=""&&senseData!=[]){
					var senseMax=senseData.sort()[0]
					var senseAdd=parseInt(senseMax/10)
					if(senseAdd==0){senseMax=1}
				}
			}

		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	});
	var personnelInfo = echarts.init(document.getElementById('personnel'));
	personnelChart(personnelInfo)
}

function getWorkInfoData() {
	sendAjaxRequest('index/workInfo', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.fault").html(jsonObj.data.workInfoData.fault);
			$("div.workOrder").html(jsonObj.data.workInfoData.workOrder);
			$("div.processed").html(jsonObj.data.workInfoData.processed);
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

function trendChart(chart,data){
    // chart.clear();
    option = {
	    tooltip: {
	        trigger: 'axis'
	    },
        legend: {
            y: 20,
            data:  ["进站客流", "出站客流"],
            textStyle: {
                fontSize: 14,
                color: '#fff'
            }
        },
        xAxis: [{
            type: "category",
            boundaryGap : true,
            splitLine: {
                show: false
            },
            data: trendTime,
            axisTick: {
                // show: false,
                alignWithLabel: true
            },
            axisLine: {
                lineStyle: {
                    color: '#fff',
                    width: 2
                }
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                // show: false
                textStyle:{
                    color: '#FFFFFF',
                    fontSize:12
                },
                interval: 0
            }
        }],
        yAxis: [{
            type: "value",
            splitNumber: 4,
            axisLine: {
                lineStyle: {
                    color: '#fff',
                    width: 1
                }
            },
            axisLabel: {
                // show: false
                textStyle:{
                    color: '#FFFFFF',
                    fontSize:12
                }
            },
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dotted'
                }
            },
            axisTick: {
                // show: false,
            },
        }],
        series: [{
            name: "进站客流",
            type: "line",
            data: inTrend,
            symbol: 'rect',
            // symbolSize: 10,
            clipOverflow: false,
            hoverAnimation: false,
            showSymbol: false,
            itemStyle: {
                normal: {
                    color: '#36B5B0'
                }
            },
            areaStyle: {
                normal: {
                    color: '#36B5B0'
                }
            }
        }, {
            name: "出站客流",
            type: "line",
            data: outTrend,
            symbol: 'rect',
            // symbolSize: 10,
            clipOverflow: false,
            hoverAnimation: false,
            showSymbol: false,
            itemStyle: {
                normal: {
                    color: '#CD6B17'
                }
            },
            areaStyle: {
                normal: {
                    color: '#CD6B17'
                }
            }
        }]
    };

    chart.setOption(option);
}


function densityChart(chart,data){
    // chart.clear();
    option = {
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            show: false
        },
        xAxis: [{
            type: 'category',
            data: ['上行站台', '下行站台', '3号口闸机', '2号口闸机'],
            axisLine: {
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#fff',
                fontSize: 14,
                interval: 0
            }
        }],
        yAxis: [{
            type: 'value',
            show: true,
            splitNumber: 5,
            axisTick: {
                show: true
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff'
                }
                
            },
            axisLabel: {
                color: '#fff',
                fontSize: 14
            },
            splitLine: {
                show: false
            }
        }],
        axisPointer: {
            show: false
        },
        series: [{
            type: 'bar',
            data: data.seriesData,
            itemStyle: {
                normal: {
                    color: function(params) { 
                        var colorList = ['#42D9B8','#FF7F00','#FE0000','#42D9B8']; 
                        return colorList[params.dataIndex] 
                    }
                }
            },
            label: {
                normal: {
                    show: true,
                    position: 'top',
                    fontSize: 14
                }
            },
            barWidth: 20
        }]
    };
    chart.setOption(option);
}

function personnelChart(chart) {
	// chart.clear();
	option = {
		    tooltip: {
		        trigger: 'axis',
		    },
		    legend: {
		    	data:['未完成计划任务','未完成感知任务',"已完成"],
	            textStyle: {
	                fontSize: 12,
	                color: '#fff'
	            }
		    },
		    xAxis: [
		        {
		            type: 'category',
		           // boundaryGap: true,
		            data: timeLine,
		            axisLine : {
						lineStyle : {
							color : '#fff'
						}
					},
		        },
		    ],
		    dataZoom: {
		        show: true,
		        start: 0,
		        end: 100,
		        height: 15,//组件高度
	            handleColor: '#fff',//h滑动图标的颜色
	            left: 60, //左边的距离
	               right: 60,//右边的距离

	            textStyle:{
	                 color:'#fff',
	                 fontSize:'12'
	                  }
		    },
		    yAxis: [
		        {
		            type: 'value',
		            scale: true,
		            name: '计划任务',
		            min: 0,
		            axisLine: {
		                lineStyle: {
		                    color: '#fff',
		                    width: 1
		                }
		            },
		            axisLabel: {
		                // show: false
		                textStyle:{
		                    color: '#FFFFFF',
		                    fontSize:12
		                }
		            },
					splitLine : {
						show : false
					}
		        },
		        {
		            type: 'value',
		            scale: true,
		            name: '感知任务',
		            min: 0,
		            axisLine: {
		                lineStyle: {
		                    color: '#fff',
		                    width: 1
		                }
		            },
		            axisLabel: {
		                // show: false
		                textStyle:{
		                    color: '#FFFFFF',
		                    fontSize:12
		                }
		            },
					splitLine : {
						show : false
					}
		        }
		    ],
		    series: [
				{
				    name:'已完成',
				    type:'bar',
				    boundaryGap: true,
				    xAxisIndex: 0,
				    yAxisIndex: 0,
				    stack:"计划任务",
				    data:planTaskDone,
				    itemStyle: {
				        normal: {
				            color:'#64BD3D'
				        },
				    },
				},
				{
				    name:'未完成计划任务',
				    type:'bar',
				    boundaryGap: true,
				    xAxisIndex: 0,
				    yAxisIndex: 0,
				    stack:"计划任务",
				    data:planTaskUndone,
				    itemStyle: {
		                normal: {
		                    color:'#ffd306',
		                },
		            },
				},
				{
		            name:'计划任务总数',
		            type:'bar',
		            xAxisIndex: 0,
		            yAxisIndex: 0,
		            data:planTaskTotal,
		            stack:"计划任务",
		            itemStyle: {
				        normal: {
				        	color:'rgba(128, 128, 128, 0)',
				        },
				    },
		            label:{
				    	normal: {
	                        show: true,
	                        formatter: function(params) {
		                    	if (params.value > 0) {
		                    		return params.value;
		                    	} else {
		                    		return '';
		                    	}
		                    }, 
	                        position: 'insideBottom',
	                        textStyle:{ color:'#fff' }
	                    },
				    },
		        },
				{
				    name:'已完成',
				    type:'bar',
				    boundaryGap: true,
				    xAxisIndex: 0,
				    yAxisIndex: 1,
				    stack:"感知任务",
				    data:senseTaskDone,
				    itemStyle: {
				        normal: {
				            color:'#64BD3D' 
				        },
				    },
				},
				{
				    name:'未完成感知任务',
				    type:'bar',
				    boundaryGap: true,
				    xAxisIndex: 0,
				    yAxisIndex: 1,
				    stack:"感知任务",
				    data:senseTaskUndone,
				    itemStyle: {
		                normal: {
		                    color:'#337ab7'
		                },
		            },
				},
		        
		        {
		            name:'感知任务总数',
		            type:'bar',
		            xAxisIndex: 0,
		            yAxisIndex: 1,
		            data:senseTaskTotal,
		            stack:"感知任务",
		            itemStyle: {
				        normal: {
				        	color:'rgba(128, 128, 128, 0)',
				        },
				    },
		            label:{
				    	normal: {
	                        show: true,
	                        formatter: function(params) {
		                    	if (params.value > 0) {
		                    		return params.value;
		                    	} else {
		                    		return '';
		                    	}
		                    }, 
	                        position: 'insideBottom',
	                        textStyle:{ color:'#fff' }
	                    },
				    },
		        },
		    ]
		};
	chart.setOption(option);
}